package ip

import (
	"gitee.com/yysf-xin/dproxy/pkg/tools"
	"io"
	"net"
	"net/http"
)

type Remote struct {
	Url string
}

func (r *Remote) ObtainIp() *Addr {
	rsp, err := http.DefaultClient.Get(r.Url)
	if rsp != nil && rsp.Body != nil {
		defer rsp.Body.Close()
	}
	if err != nil {
		tools.Log.Println("obtain ip error", err)
		return nil
	}
	b, err := io.ReadAll(rsp.Body)
	if err != nil {
		tools.Log.Println("io error", err)
	}
	tools.Log.Println("ip = ", tools.BytesToStringFast(b))
	ip := net.ParseIP(tools.BytesToStringFast(b))
	if ip == nil {
		tools.Log.Println("ip error", tools.BytesToStringFast(b))
		return nil
	}
	addr := &Addr{}
	if len(ip) == net.IPv4len {
		addr.Ip4 = ip
	} else {
		addr.Ip6 = ip
	}
	return addr
}
